package com.wfit.boot.service;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfit.boot.common.Constants;
import com.wfit.boot.controller.dto.UserDTO;
import com.wfit.boot.entity.User;
import com.wfit.boot.exception.ServiceException;
import com.wfit.boot.mapper.UserMapper;



import com.wfit.boot.utils.TokenUtils;
import org.springframework.stereotype.Service;


@Service
public class UserService extends ServiceImpl<UserMapper,User> {
    private static final Log LOG =Log.get();

    public boolean saveUser(User user) {
//       if (user.getId()==null){
//           return  save(user);
//    }else {
//           return  updateById(user);
//    }
        return saveOrUpdate(user);




    }

    public UserDTO login(UserDTO userDTO) {
        User one =getUserInfo(userDTO);
        if (one != null) {
            BeanUtil.copyProperties(one, userDTO, true);
            String token = TokenUtils.genToken(one.getId( ).toString(), one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }


}

    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one==null){
            one=new User();
            BeanUtil.copyProperties(userDTO, one, true);
            save(one);
        }
        else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }

return one;
    }
    private User getUserInfo(UserDTO userDTO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper);//list


        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(
                    Constants.CODE_500,
                    "系统错误"
            );
        }
        return one;
    }
}

//    @Autowired
//    private UserMapper userMapper;
//    public int save(User user){
//        if (user.getId()==null){
//           return userMapper.insert(user);
//        }else {
//           return userMapper.update(user);
//        }
//    }


